package com.qmock.pay.umpay.service;

import com.qmock.pay.common.DateFormat;
import com.qmock.pay.exception.SignEncException;
import com.qmock.pay.http.ExpectResponse;
import com.qmock.pay.runner.Service;
import com.qmock.pay.security.UmpayRSA;
import com.qmock.pay.umpay.UmpayStringUtils;
import com.qmock.pay.umpay.handler.UmpayHttpRequest;
import com.qmock.pay.umpay.handler.UmpayHttpResponse;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tianqing.wang
 */
public class UmpayCreditDirectPayService implements Service {
    private Logger logger = Logger.getLogger(UmpayCreditDirectPayService.class);
    private Map<String,String> defaultParams;
    private UmpayHttpRequest resquest;
    public UmpayCreditDirectPayService(UmpayHttpRequest resquest){
        this.resquest=resquest;
        this.defaultParams=new HashMap<String, String>();
        this.defaultParams.put("sign_type","RSA");
        this.defaultParams.put("mer_id",resquest.getParameterValue("mer_id"));
        this.defaultParams.put("version","4.0");
        this.defaultParams.put("trade_no", DateFormat.format("yyyyMMddHHMMSS"));
        this.defaultParams.put("order_id",resquest.getParameterValue("order_id"));
        this.defaultParams.put("mer_date",resquest.getParameterValue("mer_date"));
        this.defaultParams.put("pay_date",DateFormat.format("yyyyMMdd"));
        this.defaultParams.put("amount",resquest.getParameterValue("amount"));
        this.defaultParams.put("amt_type","RMB");
        this.defaultParams.put("pay_type","CREDITCARD");
        this.defaultParams.put("trade_state","TRADE_SUCCESS");
        this.defaultParams.put("ret_code","0000");
    }

    @Override
    public String getHttpResponseContent(ExpectResponse expectResponse) throws SignEncException {
        logger.info("读取到了配置的响应参数，进行参数转化处理....");
        Map<String,String> responseparams = expectResponse.getResponse();
        this.defaultParams.putAll(responseparams);
        String signString = UmpayStringUtils.toSignString(this.defaultParams);
        this.defaultParams.put("sign", UmpayRSA.getInstance().sign(signString));
        String responseContent = UmpayStringUtils.toString(defaultParams);
        return UmpayHttpResponse.format(responseContent);
    }

    @Override
    public String getHttpResponseContent() throws SignEncException {
        logger.info("未读取到配置的响应参数，不再进行参数转化处理....");
        String signString = UmpayStringUtils.toSignString(this.defaultParams);
        this.defaultParams.put("sign",UmpayRSA.getInstance().sign(signString));
        String responseContent = UmpayStringUtils.toString(defaultParams);
        return UmpayHttpResponse.format(responseContent);
    }

    @Override
    public Map<String, String> getResponseParameters() {
        return this.defaultParams;
    }


}
